package com.mark.util;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlCData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class XMLUtil {
    private static Logger logger = LoggerFactory.getLogger(XMLUtil.class);
    private static ObjectMapper xmlMapper = new XmlMapper();

    public static class POJO {

        private Map<String, String> map = new TreeMap<String, String>();

        @JsonAnyGetter
        @JacksonXmlCData
        public Map<String, String> get() {
            return map;
        }

        @JsonAnySetter
        public void set(String name, String value) {
            map.put(name, value);
        }
    }

    public static Map<String, String> xml2map(String xml) {
        Map<String, String> map = new HashMap<>();
        try {
            POJO pojo = xmlMapper.readValue(xml, POJO.class);
            map = pojo.get();
        } catch (Exception e) {
            logger.error("", e);
        }
        return map;
    }

    public static String map2xml(Map map) {
        try {
            String message = "<xml>\n";
            for (Object key : map.keySet()) {
                String value = map.get(key).toString();
                message = message + String.format("<%s><![CDATA[%s]]></%s>\n", key, value, key);
            }
            message = message + "</xml>";
            return message;
        } catch (Exception e) {
            logger.error("", e);
            return "";
        }
    }

    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        map.put("a", "a1");
        map.put("b", "b1");
        System.out.println(map2xml(map));
    }
}
